import logging

from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    def __init__(self,driver:webdriver):
        self.__driver=driver
    # def __init__(self, url):
    #     driver_path = "../driver/chromedriver.exe"  # 浏览器驱动地址
    #     service = Service(executable_path=driver_path)
    #     driver = webdriver.Chrome(service=service)
    #     driver.maximize_window()
    #     # 驱动自动从网络下载
    #     driver.get(url)
    #     self.__driver = driver

    # def close(self):
    #     self.__driver.quit()

    # 定位元素
    #:loc   我们定位元素的方法及值
    # WebElement  告诉调用者,这个方法返回是第一个元素
    def __find_ele(self,loc:tuple)->WebElement:
       # ele=None
       try:
         ele= WebDriverWait(self.__driver,5).until(lambda x:x.find_element(*loc))
         logging.info(f" 定位元素成功:find_ele{loc}")
         return ele
       except Exception as e:
           logging.error(f" 定位元素失败:find_ele{loc},错误原因:{e.__doc__}")

      # ele= WebDriverWait(self.__driver,5).until(lambda x:x.find_element(*loc))
      # if ele:
      #     return ele
      # else:
      #     logging.error(f" 定位元素失败:find_ele{loc}")
      #     raise  TimeoutException("定位元素失败,请检查元素的定位信息")

  #下面的所有的操作都是针对这个元素

    # #元素输入值
    def ele_input(self,loc:tuple,value:str):
        try:
            self.__find_ele(loc).send_keys(value)
            logging.info(f" 元素输入值成功:ele_input{value}")
        except Exception as e:
            logging.error(f" 元素输入值失败:ele_input{value},错误原因:{e}")

    #点击元素
    def ele_click(self,loc:tuple):
        try:
            self.__find_ele(loc).click()
            logging.info(f" 元素点击成功:ele_click")
        except Exception as e:
            logging.error(f" 元素点击失败:ele_click,错误原因:{e}")

    # 获取元素文本
    def get_ele_text(self, loc: tuple) -> str:
        try:
            element = self.__find_ele(loc)
            if element:
                text = element.text
                logging.info(f" 获取元素文本成功: {text}")
                return text
            else:
                logging.warning(f" 获取元素文本失败: 元素未找到 {loc}")
        except Exception as e:
            logging.error(f" 获取元素文本异常: {loc}, 错误原因: {e}")
            return ""
        # try:
        #     logging.info(f" 获取元素文本成功:get_ele_text")
        #     ele_text=self.__find_ele(loc)
        #     return ele_text.text
        # except Exception as e:
        #     logging.info(f" 获取元素文本失败:get_ele_text,错误原因:{e}")

    #鼠标的单击
    def mouse_click(self,loc:tuple):
        ActionChains(self.__driver).click(self.__find_ele(loc)).perform()